package cn.edu.scau.cmi.ema.service;

import cn.edu.scau.cmi.ema.base.CmiPagination;
import cn.edu.scau.cmi.ema.domain.Crawler;
import cn.edu.scau.cmi.ema.domain.Crawlerpicture;
import cn.edu.scau.cmi.ema.service.base.CmiEmaService;
import cn.edu.scau.cmi.ema.util.CmiSqlUtil;
import org.hibernate.Session;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.Query;
import java.util.*;
@Service("CrawlerService")
@Transactional

public class CrawlerServiceImpl extends CmiEmaService implements CrawlerService {
	public CrawlerServiceImpl() {
	}

	@Transactional
	public Crawler saveCrawler(Crawler crawler) {
		Set<Crawlerpicture> existingCrawlerpicturesForCrawler = new HashSet<Crawlerpicture>();

		Set<Crawlerpicture> selectedCrawlerpicturesForCrawler = crawler.getCrawlerpicturesForCrawler();

		if (crawler.getId() == null) {

			Crawler existingCrawler = crawlerDAO.findCrawlerByPhysicalPrimaryKey(crawler.getName());

			if (isEquals(crawler, existingCrawler)) {
				return existingCrawler;
			}

			crawler = crawlerDAO.store(crawler);
			crawlerDAO.flush();

			for (Crawlerpicture relatedCrawlerpicture : selectedCrawlerpicturesForCrawler) {
				relatedCrawlerpicture.setCrawler(crawler);
				crawlerpictureDAO.store(relatedCrawlerpicture);
			}
		} else {
			Crawler existingCrawler = crawlerDAO.findCrawlerByPrimaryKey(crawler.getId());

			existingCrawlerpicturesForCrawler = existingCrawler.getCrawlerpicturesForCrawler();

			Set<Crawlerpicture> prepareDeleteCrawlerpicturesForCrawler = new HashSet<Crawlerpicture>();
			Set<Crawlerpicture> prepareAddCrawlerpicturesForCrawler = new HashSet<Crawlerpicture>();

			prepareDeleteCrawlerpicturesForCrawler.addAll(selectedCrawlerpicturesForCrawler);
			prepareDeleteCrawlerpicturesForCrawler.addAll(existingCrawlerpicturesForCrawler);

			prepareAddCrawlerpicturesForCrawler.addAll(selectedCrawlerpicturesForCrawler);
			prepareAddCrawlerpicturesForCrawler.addAll(existingCrawlerpicturesForCrawler);

			prepareDeleteCrawlerpicturesForCrawler.removeAll(selectedCrawlerpicturesForCrawler);
			prepareAddCrawlerpicturesForCrawler.removeAll(existingCrawlerpicturesForCrawler);

			for (Crawlerpicture relatedCrawlerpicture : prepareAddCrawlerpicturesForCrawler) {
				relatedCrawlerpicture.setCrawler(crawler);
				crawlerpictureDAO.store(relatedCrawlerpicture);
			}

			for (Crawlerpicture relatedCrawlerpicture : prepareDeleteCrawlerpicturesForCrawler) {
				relatedCrawlerpicture.setCrawler(null);
				crawlerpictureDAO.store(relatedCrawlerpicture);
			}
			crawler = crawlerDAO.store(crawler);
			crawlerDAO.flush();
		}

		crawlerpictureDAO.flush();
		return crawler;
	}

	public void deleteCrawler(Crawler crawler) {
		crawlerDAO.remove(crawler);
		crawlerDAO.flush();
	}

	@Transactional
	public void deleteCrawlers(Set<Integer> deleteCrawlersId) {
		Query query = crawlerDAO.createNamedQuery("deleteCrawlersById", -1, -1);
		query.setParameter(1, deleteCrawlersId);
		query.executeUpdate();
	}

	@Transactional
	public Set<Crawler> loadCrawlers() {
		return crawlerDAO.findAllCrawlers();

	}

	@Transactional
	public Set<Crawler> loadReferenceCrawlers(Set<Crawler> crawlers) {
		Iterator<Crawler> crawlersIterator = crawlers.iterator();
		Set<Crawler> referencedCrawlers = new HashSet<>();
		while (crawlersIterator.hasNext()) {
			Crawler currentCrawler = crawlersIterator.next();

			if (!currentCrawler.getCrawlerpicturesForCrawler().isEmpty()) {
				referencedCrawlers.add(currentCrawler);
				continue;
			}
		}
		return referencedCrawlers;
	}

	public Set<Crawler> loadCrawlersByIdSet(Set<Integer> crawlerIdSet) {

		Iterator<Integer> crawlerIdIterator = crawlerIdSet.iterator();
		Set<Crawler> crawlerSet = new HashSet<>();
		while (crawlerIdIterator.hasNext()) {
			Integer id = crawlerIdIterator.next();
			Crawler currentCrawler = crawlerDAO.findCrawlerById(id);
			crawlerSet.add(currentCrawler);
		}
		return crawlerSet;
	}

	@Transactional
	public List<Crawler> findAllCrawlers(Integer startResult, Integer maxRows) {
		return new java.util.ArrayList<Crawler>(crawlerDAO.findAllCrawlers(startResult, maxRows));
	}

	@Transactional
	public Crawler findCrawlerByPrimaryKey(Integer id) {
		return crawlerDAO.findCrawlerByPrimaryKey(id);
	}

	@Transactional
	public Integer countCrawlers() {
		return ((Long) crawlerDAO.createQuerySingleResult("select count(o) from Crawler o").getSingleResult())
				.intValue();
	}

	@Transactional
	public Integer countCrawlers(CmiPagination page) {
		String sql = CmiSqlUtil.createCountHql(page, Crawler.class);
		return ((Long) crawlerDAO.createQuerySingleResult(sql).getSingleResult()).intValue();
	}

	/**
	 * search for name with ajax
	 *
	 */
	@Transactional
	public Integer countCrawlersByName(String queryName) {
		Query query = crawlerDAO.createNamedQuery("countCrawlersByName", -1, -1);
		query.setParameter(1, queryName);
		return new Long((long) query.getSingleResult()).intValue();
	}

	@Transactional
	public Integer countCrawlersByDetachedCriteria(CmiPagination page) {
		DetachedCriteria detachedCriteria = CmiSqlUtil.createDetachedCriteria(page, Crawler.class);
		Session session = (Session) entityManager.getDelegate();
		detachedCriteria.setProjection(Projections.rowCount());
		return new Long((long) detachedCriteria.getExecutableCriteria(session).uniqueResult()).intValue();
	}

	public Map<String, ?> loadCrawlerObjectReferencedSet(Crawler crawler) {
		HashMap<String, Object> objectReferencedSetMap = new HashMap<>();

		Set<Integer> crawlerpicturesIds = new HashSet<Integer>();
		for (Crawlerpicture obj : crawler.getCrawlerpicturesForCrawler()) {

			crawlerpicturesIds.add(obj.getId());
		}
		objectReferencedSetMap.put("crawlerpicturesIds", crawlerpicturesIds);

		return objectReferencedSetMap;
	}

	public Map<String, ?> loadCrawlerClassReferencedSet(Crawler crawler) {
		HashMap<String, Object> classReferencedSetMap = new HashMap<>();
		classReferencedSetMap.put("crawlerpictures", crawlerpictureDAO.findAllCrawlerpictures());

		return classReferencedSetMap;
	}

	public boolean isEquals(Crawler crawler, Object obj) {
		if (obj == crawler)
			return true;
		if (!(obj instanceof Crawler))
			return false;
		Crawler comparedCrawler = (Crawler) obj;
		if (!CheckPropertyEqual(crawler.getName(), comparedCrawler.getName())) {
			return false;
		}
		return true;
	}

	public static <T> boolean CheckPropertyEqual(T originProperty, T comparedProperty) {
		// 基本类型经过参数传递后会自动装箱
		String[] className = originProperty.getClass().getName().split("\\.");
		if (className[0].equals("java") && className[1].equals("math")) {
			return ((Comparable) originProperty).compareTo(comparedProperty) == 0 ? true : false;
		} else {
			return originProperty.equals(comparedProperty);
		}
	}
}

